/***************************************************************************
 *   Copyright (C) 2010 by Oleg Goncharov  *
 *   $EMAIL$                           *                          
 *                                                                         *
 *   This file is part of ChessVision.                                     *
 *                                                                         *
 *   ChessVision is free software; you can redistribute it and/or modify   *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include <time.h>
#include "cimagecamthread.h"
#include "error/cerror.h"

CImageCamThread::CImageCamThread(int cam, int sleep_per_frame_ms)
{
	if ( !(d_camera = cvCreateCameraCapture(cam))) throw Errors::CError("Unable capture from camera.");
	pthread_mutex_init(&d_img_mutex, 0);
	d_sleep = 1000000*sleep_per_frame_ms;
	
	int iret = pthread_create(&d_thread, NULL, &CImageCamThread::run, (void*) this);
	if (iret) throw Errors::CError("pthread create error");
}

CImageCamThread::~CImageCamThread() {
	if (pthread_cancel(d_thread)) Errors::CError("pthread cancellation error");
	cvReleaseCapture(&d_camera);
}

IplImage * CImageCamThread::GrabFrame() {
	Clear();
	
	pthread_mutex_lock(&d_img_mutex);
	IplImage * tmp = cvQueryFrame(d_camera);
	img = cvCloneImage(tmp);
	pthread_mutex_unlock(&d_img_mutex);
	
	cvFlip(img);
	return img;
}

void * CImageCamThread::run(void * thisptr) {
	static_cast<CImageCamThread*>(thisptr)->ImgReader();
	return 0;
}

void CImageCamThread::ImgReader() {
	pthread_mutex_t wait_mutex = PTHREAD_MUTEX_INITIALIZER;
	pthread_cond_t wait_cond  = PTHREAD_COND_INITIALIZER;
	pthread_mutex_lock(&wait_mutex);
	timespec ts;
	
	for (;;) {
		pthread_mutex_lock(&d_img_mutex);
		cvQueryFrame(d_camera);
		pthread_mutex_unlock(&d_img_mutex);
		
		clock_gettime(CLOCK_REALTIME, &ts);
		ts.tv_nsec += d_sleep;
		pthread_cond_timedwait(&wait_cond, &wait_mutex, &ts);
	}
}
